// search相关的仓库

import { Article } from '@/types/data'
import { RootAction } from '@/types/store'
import { getHistory } from '@/utils/history'

type InitType = {
  suggestion: string[]
  history: string[]
  results: Article[]
}

const initValue: InitType = {
  suggestion: [],
  history: getHistory(), // 搜索历史存在仓库， 存在本地
  results: [], // 存搜索结果 文章数组
}

export default function searchReducer(
  state: InitType = initValue,
  action: RootAction
): InitType {
  // { type: 'search/set_suggestion', payload: res.data.data.options }

  if (action.type === 'search/set_suggestion') {
    return {
      ...state,
      suggestion: action.payload,
    }
  }

  // { type: 'search/set_history', payload: ['vue', 'react'] }
  if (action.type === 'search/set_history') {
    return {
      ...state,
      history: action.payload,
    }
  }

  // { type: 'search/clear_history' }
  if (action.type === 'search/clear_history') {
    return {
      ...state,
      history: [],
    }
  }

  if (action.type === 'search/set_results') {
    return {
      ...state,
      results: [...state.results, ...action.payload], // 追加数据
    }
  }

  if (action.type === 'search/clear_results') {
    return {
      ...state,
      results: [], // 清空数据
    }
  }

  return state
}
